import type { ComponentStyleIdType } from '../../types/interfaces'
import type { FilterGroup, FilterProps, SelectOption } from './types'
import { UIComponent } from '../../lib/abstract'
import { ComponentStyleId } from '../../types/constants'
import { SYMBOLS } from '../../types/interfaces'
import { styles } from './styles'
import { DEFAULT_FILTER_PROPS } from './types'

export class Filter extends UIComponent<FilterProps> {
  id: string = 'filter'
  readonly description: string = '多选筛选器'
  readonly styleId: string = ComponentStyleId[this.name]
  private selectedValues: Record<string, string[]> = {}
  private activeMenu: string | null = null

  get name(): ComponentStyleIdType {
    return 'Filter'
  }

  get className(): string {
    return `${this.props.id}-custom-filter`
  }

  constructor(props: FilterProps) {
    super({
      ...DEFAULT_FILTER_PROPS,
      ...props,
    })

    // 初始化选中状态
    this.props.filterGroups.forEach((group: FilterGroup) => {
      this.selectedValues[group.id] = group.defaultValues || []
    })

    // 注册样式
    this.registerStyles()
  }

  ELEMENT_SELECTORS = {

  }

  render(): string {
    const position = this.props.position === 'right' ? 'flex-end' : 'flex-start'

    return `
      <div class="${this.className}" style="justify-content: ${position};">
        ${this.props.filterGroups.map((group: FilterGroup) => this.renderFilterGroup(group)).join('')}
      </div>
    `
  }

  private renderFilterGroup(group: FilterGroup): string {
    const isActive = this.activeMenu === group.id
    const hasChildren = group.options.length > 0
    const nonZeroCountOptions = group.options.filter(opt => opt.count && opt.count > 0).length

    return `
      <div class="filter-group ${isActive ? 'active' : ''}" data-id="${group.id}">
        <button class="filter-menu-button" data-id="${group.id}">
          <span class="filter-icon">${group.icon || SYMBOLS.STATUS.UNCHECKED}</span>
          <span class="filter-label">${group.label}</span>
          ${group.showCount !== false && nonZeroCountOptions > 0
            ? `<span class="group-count">（${nonZeroCountOptions}）</span>`
            : ''}
          ${hasChildren
            ? `<span class="dropdown-icon">${SYMBOLS.UI.SEARCH}</span>`
            : ''}
        </button>
        ${hasChildren ? this.renderOptions(group) : ''}
      </div>
    `
  }

  private renderOptions(group: FilterGroup): string {
    const isMultiSelect = group.selectionMode === 'multiple'

    return `
      <div class="filter-options">
        ${isMultiSelect ? this.renderSelectAllButton(group.id) : ''}
        ${group.options.map(option => this.renderOption(option, group.id)).join('')}
      </div>
    `
  }

  private renderSelectAllButton(groupId: string): string {
    const allValues = this.props.filterGroups
      .find((g: FilterGroup) => g.id === groupId)
      ?.options
      .map((opt: SelectOption) => opt.value) || []
    const isAllSelected = allValues.every((val: string) =>
      this.selectedValues[groupId]?.includes(val),
    )

    return `
      <div class="filter-select-all" data-group="${groupId}">
        <span class="select-all-checkbox ${isAllSelected ? 'checked' : ''}">
          ${isAllSelected ? SYMBOLS.STATUS.CHECK_MARK : ''}
        </span>
        <span class="select-all-label">全选</span>
      </div>
    `
  }

  private renderOption(option: SelectOption, groupId: string): string {
    const isSelected = this.selectedValues[groupId]?.includes(option.value)
    const selectionMode = this.props.filterGroups.find((g: FilterGroup) => g.id === groupId)?.selectionMode || 'multiple'
    const showCount = this.props.filterGroups.find((g: FilterGroup) => g.id === groupId)?.showCount ?? true

    return `
      <div class="filter-option ${isSelected ? 'selected' : ''} ${selectionMode === 'single' ? 'single-mode' : ''}" data-group="${groupId}" data-value="${option.value}"      >
        ${selectionMode === 'multiple' ? this.renderCheckbox(isSelected) : ''}
        ${option.icon ? `<span class="option-icon">${option.icon}</span>` : ''}
        <span class="option-label">${option.label}</span>
        ${showCount && option.count !== undefined
          ? `<span class="option-count">(${option.count})</span>`
          : ''}
      </div>
    `
  }

  private renderCheckbox(checked: boolean): string {
    return `
      <span class="filter-checkbox ${checked ? 'checked' : ''}">
        ${checked ? SYMBOLS.STATUS.CHECK_MARK : ''}
      </span>
    `
  }

  bindEvents(): void {
    // 1. 一级菜单点击
    this.$element
      ?.off()
      .on('click', '.filter-menu-button', (e) => {
        // 阻止冒泡事件
        e.stopPropagation()

        const groupId = $(e.currentTarget).data('id')
        this.toggleFilterMenu(groupId)
      })// 2. 二级选项点击
      .on('click', '.filter-option', (e) => {
        e.stopPropagation() // 阻止冒泡

        const $option = $(e.currentTarget)
        const groupId = $option.data('group')
        const value = $option.data('value')
        this.handleOptionSelect(groupId, value)
      })

    // 3.添加全选按钮点击事件
    this.$element?.on('click', '.filter-select-all', (e) => {
      e.stopPropagation()
      const groupId = $(e.currentTarget).data('group')
      this.handleSelectAll(groupId)
    })

    // 4.修改文档点击事件，添加延迟
    $(document).off('click.filter').on('click.filter', (e) => {
      if (!$(e.target).closest('.filter-group').length) {
        setTimeout(() => this.closeAllMenus(), 100)
      }
    })

    // 5. 鼠标移出二级菜单自动关闭
    this.$element?.on('mouseleave', '.filter-options', (e) => {
      // 延迟检查以确保不是移动到子菜单项
      setTimeout(() => {
        const $submenu = $(e.currentTarget)
        if (this.activeMenu !== null && !$submenu.find(':hover').length) {
          this.closeAllMenus()
        }
      }, 100)
    })
  }

  private handleSelectAll(groupId: string): void {
    const group = this.props.filterGroups.find((g: FilterGroup) => g.id === groupId)
    if (!group || group.selectionMode !== 'multiple')
      return

    const allValues = group.options.map((opt: SelectOption) => opt.value)
    const currentValues = this.selectedValues[groupId] || []

    // 判断是否已经全选
    const isAllSelected = allValues.every((val: string) => currentValues.includes(val))

    // 切换全选状态
    this.selectedValues[groupId] = isAllSelected ? [] : [...allValues]

    // 更新UI状态
    this.updateOptionStates(groupId)
    this.props.onChange?.(this.selectedValues)
  }

  private toggleFilterMenu(groupId: string): void {
    if (this.activeMenu === groupId) {
      this.closeAllMenus()
    }
    else {
      this.closeAllMenus()
      this.activeMenu = groupId

      $(`.filter-group[data-id="${groupId}"]`).addClass('active')

      // 添加动画效果
      $(`.filter-group[data-id="${groupId}"] .filter-options`)
        .css('opacity', 0)
        .animate({ opacity: 1 }, 200)
    }
  }

  private handleOptionSelect(groupId: string, value: string): void {
    const group = this.props.filterGroups.find((g: FilterGroup) => g.id === groupId)

    if (!group)
      return

    const currentValues = this.selectedValues[groupId] || []
    let newValues: string[]

    if (group.selectionMode === 'single') {
      newValues = currentValues.includes(value) ? [] : [value]
    }
    else {
      newValues = currentValues.includes(value)
        ? currentValues.filter(v => v !== value)
        : [...currentValues, value]
    }

    this.selectedValues[groupId] = newValues
    this.updateOptionStates(groupId)
    this.props.onChange?.(this.selectedValues)
  }

  private updateOptionStates(groupId: string): void {
    const currentValues = this.selectedValues[groupId] || []

    const allValues = this.props.filterGroups
      .find((g: FilterGroup) => g.id === groupId)
      ?.options
      .map((opt: SelectOption) => opt.value) || []

    // 更新选项状态
    $(`.filter-option[data-group="${groupId}"]`).each((_, el) => {
      const $option = $(el)
      const value = $option.data('value')
      const isSelected = currentValues.includes(value)

      // 更新选中状态类
      $option.toggleClass('selected', isSelected)

      // 更新复选框状态
      $option.find('.filter-checkbox')
        .toggleClass('checked', isSelected)
        .html(isSelected ? SYMBOLS.STATUS.CHECK_MARK : '')

      $option.find('.filter-checkbox').toggleClass('checked', currentValues.includes(value))
    })

    // 更新全选按钮状态
    const isAllSelected = allValues.every((val: string) => currentValues.includes(val))
    $(`.filter-select-all[data-group="${groupId}"] .select-all-checkbox`)
      .toggleClass('checked', isAllSelected)
      .html(isAllSelected ? SYMBOLS.STATUS.CHECK_MARK : '')
  }

  private closeAllMenus(): void {
    this.activeMenu = null
    this.$element?.find('.filter-group').removeClass('active')
  }

  // 更新选项计数
  public updateOptionCounts(groupId: string, counts: Record<string, number>): void {
    const group = this.props.filterGroups.find((g: FilterGroup) => g.id === groupId)

    if (!group)
      return

    // 更新选项计数
    group.options.forEach((option: SelectOption) => {
      option.count = counts[option.value] || 0
    })

    // 重新渲染受影响的组
    $(`.filter-group[data-id="${groupId}"]`).replaceWith(this.renderFilterGroup(group))

    // 重新绑定事件
    this.bindEvents()
  }

  getSelectedValues(): Record<string, string[]> {
    return this.selectedValues
  }

  reset(): void {
    this.props.filterGroups.forEach((group: FilterGroup) => {
      this.selectedValues[group.id] = group.defaultValues || []
    })
    this.updateAllOptionStates()
    this.closeAllMenus()
  }

  private updateAllOptionStates(): void {
    this.props.filterGroups.forEach((group: FilterGroup) => {
      this.updateOptionStates(group.id)
    })
  }

  destroy(): void {
    $(document).off('click', this.closeAllMenus.bind(this))
    super.destroy()
  }

  getStyles(): string {
    return styles(this.className)
  }
}
